<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { unitApi, positionApi } from '@T2/service/api.ts';
import { buildPositionUnitTree, deepCopy } from '@T2/utils/utils.ts';
import type Node from 'element-plus/es/components/tree/src/model/node';
import type { ElTree } from 'element-plus';

const props = withDefaults(defineProps<{
  defaultLoadUnit?: null | number;
  clearable?: boolean;
}>(), {
  defaultLoadUnit: null,
  clearable: false,
});
const emits = defineEmits<{
  (event: 'current-change', data: TreeNode, node: Node): void;
  (event: 'clear'): void;
  (event: 'unitlist-change', tree: UnitType[]): void;
  (event: 'tree-change', tree: TreeNode[]): void;
}>();

interface UnitType {
  id: number;
  name: string;
  code: string;
  positon: null | number;
  x: string;
  y: string;
  project: number;
  [key: string]: any;
}
interface PositionType {
  id: number;
  name: string;
  project: number;
  parent: null | number;
  [key: string]: any;
}
interface TreeNode {
  id: number;
  key: string;
  name: string;
  project: number;
  children?: TreeNode[];
  [key: string]: any;
}
const Resd = reactive({
  tree: [] as TreeNode[],
  currentID: '' as string,
  value: null,
});
onMounted(() => {
  Promise.all([loadUnitList(), getPosition()]).then((res: any) => {
    const units = res[0] as UnitType[], positions = res[1] as PositionType[];
    emits('unitlist-change', deepCopy(res[0]));
    Resd.tree = buildPositionUnitTree(units, positions, false) as TreeNode[];
    emits('tree-change', deepCopy(Resd.tree));
    setTimeout(() => {
      if (props.defaultLoadUnit && units.find(i => i.id === props.defaultLoadUnit)) {
        Resd.currentID = props.defaultLoadUnit + 'unit';
        treeRef.value!.setCurrentKey(Resd.currentID);
      } else if (!props.clearable && units.length) {
        Resd.currentID = units[0].id + 'unit';
        treeRef.value!.setCurrentKey(Resd.currentID);
      }
    }, 100);
    
  });
});
const loadUnitList = () => {
  return new Promise((resolve, reject) => {
    unitApi({
      method: 'get',
      params: {},
    }).then((res: any) => {
      resolve(res.results || []);
    }).catch(e => {
      reject(e);
    });
  });
}
const getPosition = () => {
  return new Promise((resolve, reject) => {
    positionApi({
      method: 'get',
      params: {
        ordering: 'id',
      }
    }).then((res: any) => {
      resolve(res.results || []);
    }).catch(e => {
      reject(e);
    });
  });
}

const treeRef = ref<InstanceType<typeof ElTree> | null>(null);
const handleChange = (data: TreeNode, node: Node) => {
  if (data.hasOwnProperty('positon')) {
    emits('current-change', data, node);
  }
}
const handleClear = () => {
  let key = treeRef.value!.getCurrentKey();
  if (key) {
    treeRef.value!.setChecked(key, false, true);
  }
  emits('clear');
}
</script>

<template>
  <div class="filter-tree">
    <el-tree-select
      ref="treeRef"
      node-key="key"
      placeholder="请选择一个站点"
      :fit-input-width="true"
      :teleported="false"
      :clearable="props.clearable"
      filterable
      accordion
      :highlight-current="true"
      :props="{label: 'name'}"
      v-model="Resd.currentID"
      :data="Resd.tree"
      @current-change="handleChange"
      @clear="handleClear"
    />
  </div>
</template>

<style lang="scss" scoped>
.filter-tree {
  width: 250px;
  margin-right: 20px;
  :deep(.el-icon.el-select__caret.el-select__icon) {
    display: inline-flex;
  }
}
:deep(.el-select) {
  height: 32px;
  .el-select__wrapper {
    padding-left: 35px;
    background-color: transparent;
    box-shadow: 0 0 0 1px #025A5A inset;
    &::before {
      content: '';
      background: url('@T2/assets/common/search-white.png') no-repeat center;
      background-size: 100% 100%;
      position: absolute;
      width: 20px;
      height: 20px;
      left: 5px;
      top: 50%;
      transform: translateY(-50%);
    }
  }
}
:deep(.el-popper) {
  background-color: #0D2127;
  box-shadow: 0px 4px 8px 0px #003940;
  border-radius: 4px;
  border: 1px solid #1A4552;
  .el-select-dropdown .el-select-dropdown__item {
    font-size: 14px;
    color: #999999;
    &.is-selected {
      color: #FFFFFF;
      font-weight: 400;
    }
    &.is-disabled {
      color: rgba(255,255,255,0.4);
    }
  }
  .el-select-dropdown__wrap {
    max-height: 450px;
  }
  .el-popper__arrow::before {
    border-top-color: #1A4552;
    border-left-color: #1A4552;
    background-color: #0D2127;
  }
}
:deep(.el-tree) {
  background-color: transparent;
  .el-tree-node__content {
    height: 30px;
    &:hover {
      background-color: #122E36;
      cursor: default;
    }
  }
  .el-tree-node {
    padding: 2px 0;
    margin: 0;
    &.is-current>.el-tree-node__content {
      background-color: #122E36;
    }
    &:focus>.el-tree-node__content {
      background-color: transparent;
    }
  }
  .el-icon {
    font-size: 14px;
    margin-right: 5px;
  }
  .el-tree-node__label {
    font-size: 12px;
    color: #2C2C2C;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>